package com.aaie.gru.theme.controller;


import com.aaie.gru.getui.PushtoSingle;
import com.aaie.gru.gruenum.UserType;
import com.aaie.gru.response.ResMessage;
import com.aaie.gru.theme.entity.*;
import com.aaie.gru.theme.service.IGruSysThemeConfigService;
import com.aaie.gru.theme.service.IGruSysThemeFeedbackService;
import com.aaie.gru.theme.service.IGruSysThemeService;
import com.aaie.gru.user.entity.GruSysGuardian;
import com.aaie.gru.user.entity.GruSysUser;
import com.aaie.gru.user.service.IGruSysUserService;
import com.aaie.gru.util.CommonUtil;
import com.aaie.gru.util.ConstantUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.logging.Logger;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author lvxing
 * @since 2019-08-09
 */
@Api(tags = "主题反馈模块")
@RestController
@RequestMapping("/theme")
@Slf4j
public class GruSysThemeFeedbackController {

    @Autowired
    IGruSysThemeFeedbackService gruSysThemeFeedbackService;

    @Autowired
    IGruSysThemeService gruSysThemeService;

    @Autowired
    IGruSysThemeConfigService iGruSysThemeConfigService;

    @Autowired
    IGruSysUserService gruSysUserService;

    /**
     * 按条件获取主题反馈信息
     *
     * @param param
     * @return
     */
    @ApiOperation(value = "获取主题反馈列表", notes = "获取主题反馈列表")
    @PostMapping("/getGruSysThemeFeedbackList")
    public String getGruSysThemeFeedbackList(@RequestBody GruSysThemeFeedbackDto param,HttpSession session) {
        try {
            GruSysThemeConfig gruSysThemeConfig = new GruSysThemeConfig();
            String currentUserId = CommonUtil.getUser(session).getUserId();
            gruSysThemeConfig.setCurrentUserId(currentUserId);
            gruSysThemeConfig.setThemeId(param.getThemeId());
            gruSysThemeConfig.setThemeNew(ConstantUtil.THEME_NEW_N);
            QueryWrapper<GruSysThemeConfig> queryWrapperGrySysThemeConfig = new QueryWrapper<>();
            queryWrapperGrySysThemeConfig.eq("theme_id",param.getThemeId());
            queryWrapperGrySysThemeConfig.eq("current_user_id",currentUserId);
            queryWrapperGrySysThemeConfig.eq("theme_type",ConstantUtil.THEME_TYPE_FEEDBACK);
            int count = iGruSysThemeConfigService.count(queryWrapperGrySysThemeConfig);
            if(count > 0){
                iGruSysThemeConfigService.update(gruSysThemeConfig,queryWrapperGrySysThemeConfig);
            }
/*            if(count == 0){
                iGruSysThemeConfigService.saveOrUpdate(gruSysThemeConfig);
            }else{
                iGruSysThemeConfigService.update(gruSysThemeConfig,queryWrapperGrySysThemeConfig);
            }*/

            IPage<GruSysThemeFeedbackVo> page = gruSysThemeFeedbackService.getGruSysThemeFeedbackVoList(param);
            List<GruSysThemeFeedbackVo> gruSysThemeFeedbackVoList = page.getRecords();
            if(page.getCurrent() == 1){
                Collections.sort(gruSysThemeFeedbackVoList, Comparator.comparing(GruSysThemeFeedbackVo::getUpdateTimeSort));
            }

            return ResMessage.ok(gruSysThemeFeedbackVoList, param.getCurrent(), param.getSize(), page.getTotal());
        } catch (BeansException e) {
            e.printStackTrace();
            return ResMessage.error("/theme/getGruSysThemeFeedbackList报错", 500);
        }

    }

    /**
     * 添加主题反馈数据
     *
     * @param gruSysThemeFeedback
     * @return
     */
    @ApiOperation(value = "添加主题反馈数据", notes = "添加主题反馈数据")
    @PostMapping("/addGruSysThemeFeedback")
    public String addGruSysThemeFeedback(@RequestBody GruSysThemeFeedback gruSysThemeFeedback, HttpSession session) {
        try {
            if (StringUtils.isNotEmpty(gruSysThemeFeedback.getThemeFeedbackId())) {
                return ResMessage.error("新增的数据不能有主键id", 200);
            }
            // 主题id不能为空
            if (StringUtils.isEmpty(gruSysThemeFeedback.getThemeId())) {
                return ResMessage.error("主题id不能为空", 200);
            }
            String updateTime = CommonUtil.generateLocalDateTimeUS();
            long updateTimeSort = CommonUtil.generateCurrentTimeMillis();
            String userIdStr = CommonUtil.getUser(session).getUserId();
            String username = CommonUtil.getUser(session).getUserName();
            // 发送人名称
            gruSysThemeFeedback.setThemeFeedbackSendName(username);
            // 发送人角色
            String userType = CommonUtil.getUser(session).getUserType();
            gruSysThemeFeedback.setThemeRoleName(userType);
            // 下方是通用代码
            gruSysThemeFeedback.setCreateName(username);
            gruSysThemeFeedback.setCreateTime(updateTime);
            gruSysThemeFeedback.setCreateTimeSort(updateTimeSort);
            gruSysThemeFeedback.setUpdateName(username);
            gruSysThemeFeedback.setUpdateTime(updateTime);
            gruSysThemeFeedback.setUpdateTimeSort(updateTimeSort);
            boolean save = gruSysThemeFeedbackService.themeFeedBackInfo(gruSysThemeFeedback,userIdStr,userType);
            if (!save) {
                return ResMessage.error("数据插入失败", 200);
            }
            try {
                log.info("=========================>>>>>>>>>>>>>>userType:{}", userType);
                // 推送消息
                if (UserType.STAFF.getValue().equals(userType)) {
                    String themeId = gruSysThemeFeedback.getThemeId();
                    log.info("=========================>>>>>>>>>>>>>>themeId:{}", themeId);
                    String themeFeedbackReceiveId = gruSysThemeFeedback.getThemeFeedbackReceiveId();
                    log.info("=========================>>>>>>>>>>>>>>themeFeedbackReceiveId:{}", themeFeedbackReceiveId);
                    GruSysUser parent = gruSysUserService.getById(themeId);
                    GruSysUser guardian = gruSysUserService.getById(themeFeedbackReceiveId);
                    if (parent != null && StringUtils.isNotEmpty(parent.getUserClientId())) {
                        log.info("=========================>>>>>>>>>>>>>>parent.getUserClientId()start:{}", parent.getUserClientId());
                        PushtoSingle.pushtoSingle("消息反馈", "您收到新的消息反馈，请及时查收！", "{\"bizType\":\"108\"}", parent.getUserClientId(), parent.getPlatform());
                        log.info("=========================>>>>>>>>>>>>>>parent.getUserClientId()end:{}", parent.getUserClientId());
                    }
                    if (guardian != null && StringUtils.isNotEmpty(guardian.getUserClientId())) {
                        log.info("=========================>>>>>>>>>>>>>>guardian.getUserClientId()start:{}", guardian.getUserClientId());
                        PushtoSingle.pushtoSingle("消息反馈", "您收到新的消息反馈，请及时查收！", "{\"bizType\":\"108\"}", guardian.getUserClientId(), guardian.getPlatform());
                        log.info("=========================>>>>>>>>>>>>>>guardian.getUserClientId()end:{}", guardian.getUserClientId());
                    }
                } else if (UserType.PARENT.getValue().equals(userType)) {
                    String themeFeedbackReceiveId = gruSysThemeFeedback.getThemeFeedbackReceiveId();
                    log.info("=========================>>>>>>>>>>>>>>themeFeedbackReceiveId:{}", themeFeedbackReceiveId);
                    GruSysUser guardian = gruSysUserService.getById(themeFeedbackReceiveId);
                    if (guardian != null && StringUtils.isNotEmpty(guardian.getUserClientId())) {
                        log.info("=========================>>>>>>>>>>>>>>guardian.getUserClientId()start:{}", guardian.getUserClientId());
                        PushtoSingle.pushtoSingle("消息反馈", "您收到新的消息反馈，请及时查收！", "{\"bizType\":\"108\"}", guardian.getUserClientId(), guardian.getPlatform());
                        log.info("=========================>>>>>>>>>>>>>>guardian.getUserClientId()end:{}", guardian.getUserClientId());
                    }
                } else if (UserType.GUARDIAN.getValue().equals(userType)) {
                    String themeId = gruSysThemeFeedback.getThemeId();
                    log.info("=========================>>>>>>>>>>>>>>themeId:{}", themeId);
                    GruSysUser parent = gruSysUserService.getById(themeId);
                    if (parent != null && StringUtils.isNotEmpty(parent.getUserClientId())) {
                        log.info("=========================>>>>>>>>>>>>>>parent.getUserClientId()start:{}", parent.getUserClientId());
                        PushtoSingle.pushtoSingle("消息反馈", "您收到新的消息反馈，请及时查收！", "{\"bizType\":\"108\"}", parent.getUserClientId(), parent.getPlatform());
                        log.info("=========================>>>>>>>>>>>>>>parent.getUserClientId()end:{}", parent.getUserClientId());
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return ResMessage.ok(gruSysThemeFeedback);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/addGruSysThemeFeedback报错", 500);
        }
    }

    /**
     * 更新主题反馈数据
     *
     * @param gruSysThemeFeedback
     * @return
     */
    @ApiOperation(value = "更新主题反馈数据", notes = "更新主题反馈数据")
    @PostMapping("/editGruSysThemeFeedback")
    public String editGruSysThemeFeedback(@RequestBody GruSysThemeFeedback gruSysThemeFeedback, HttpSession session) {
        GruSysGuardian result = null;
        try {
            if (StringUtils.isEmpty(gruSysThemeFeedback.getThemeFeedbackId())) {
                return ResMessage.error("更新的数据必须有主键id", 200);
            }
            // 主题id不能为空
            if (StringUtils.isEmpty(gruSysThemeFeedback.getThemeId())) {
                return ResMessage.error("主题id不能为空", 200);
            }
            gruSysThemeFeedback.setUpdateName(CommonUtil.getUser(session).getUserName());
            gruSysThemeFeedback.setUpdateTime(CommonUtil.generateLocalDateTime());
            gruSysThemeFeedback.setUpdateTimeSort(CommonUtil.generateCurrentTimeMillis());
            boolean b = gruSysThemeFeedbackService.updateById(gruSysThemeFeedback);
            if (!b) {
                return ResMessage.error("数据更新失败", 200);
            }
            return ResMessage.ok(gruSysThemeFeedback);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/editGruSysThemeFeedback报错", 500);
        }

    }

    @ApiOperation(value = "按id主题反馈数据", notes = "按id主题反馈数据")
    @GetMapping("/getGruSysThemeFeedback")
    public String getGruSysThemeFeedback(String themeFeedbackId) {
        try {
            if (StringUtils.isEmpty(themeFeedbackId)) {
                return ResMessage.error("获取数据必须有主键id", 200);
            }
            GruSysThemeFeedback gruSysThemeFeedback = gruSysThemeFeedbackService.getById(themeFeedbackId);

            if (gruSysThemeFeedback == null) {
                return ResMessage.error("获取失败", 200);
            }
            return ResMessage.ok(gruSysThemeFeedback);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/getGruSysThemeFeedback报错", 500);
        }

    }

    @ApiOperation(value = "删除主题反馈数据", notes = "删除主题反馈数据")
    @PostMapping("/delGruSysThemeFeedback")
    public String delGruSysThemeFeedback(@RequestBody GruSysThemeFeedback gruSysThemeFeedback) {
        try {
            if (StringUtils.isEmpty(gruSysThemeFeedback.getThemeFeedbackId())) {
                return ResMessage.error("删除数据必须有主键id", 200);
            }
            boolean b = gruSysThemeFeedbackService.removeById(gruSysThemeFeedback.getThemeFeedbackId());
            if (b) {
                return ResMessage.ok("删除数据成功");
            }
            return ResMessage.error("删除数据失败", 200);
        } catch (Exception e) {
            e.printStackTrace();
            return ResMessage.error("/theme/delGruSysThemeFeedback报错", 500);
        }

    }

}
